package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    //本地注入 Redis
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPast;

    //新增套餐
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //先在套餐表里添加套餐
         setmealDao.add(setmeal);

        //再在中间表里将套餐ID与检查组ID联系起来
        //获取套餐自增后的ID
        Integer setmealId = setmeal.getId();
        //调用建立关系方法
        this.setSetmealAndCheckGroup(setmealId,checkgroupIds);
        
        //获取图片名称
        String fileName = setmeal.getImg();
        //调用自定义类将文件名存储到小集合中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //当进行添加方法时会执行静态页面刷新方法
        generateMobileStaticHtml();
    }
    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //生成静态页面之前查询套餐
        List<Setmeal> list = setmealDao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
       //生成套餐页面详情页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal>list){
     Map map=new HashMap();
     map.put("setmealList",list);
     generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }
    //生成详情页面
    public void generateMobileSetmealDetailHtml(List<Setmeal>list){
        for (Setmeal setmeal : list) {
            Map map=new HashMap();
            map.put("setmeal",setmealDao.findAllById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }

    }

    //生成通用静态页面方法
    public void generteHtml(String templateName,String htmlPageName,Map map){
        //获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out=null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out=new FileWriter(new File(outPutPast+"/"+htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //获取当前页
        Integer currentPage = queryPageBean.getCurrentPage();
        //获取一页多少数据
        Integer pageSize = queryPageBean.getPageSize();
        //获取查找关键字
        String queryString = queryPageBean.getQueryString();
        //利用分页助手进行分页
        PageHelper.startPage(currentPage,pageSize);
        //调用dao层方法
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        long total = page.getTotal();
        List<Setmeal> rows = page.getResult();
        return new PageResult(total,rows);
    }

    //删除套餐
    @Override
    public void delete(Integer id) {
        //解除套餐与检查组的关系
        setmealDao.upsetSetmealAndCheckGroup(id);
        //删除套餐
        setmealDao.delete(id);
    }

    //按Id查询
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }
    //根据套餐ID查询关联表中检查组ID
    @Override
    public List<Integer> findCheckGroupIdBySetmealId(Integer id) {

        return setmealDao.findCheckGroupIdBySetmealId(id);
    }

    //编辑
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改套餐
        setmealDao.edit(setmeal);
        //消除 检查组与套餐的联系
        //获取套餐ID
        Integer setmealId=setmeal.getId();
        //通过检查组Id 删除 关联表中的 所有有关系的对象
        setmealDao.upsetSetmealAndCheckGroup(setmealId);

        //调用建立关系方法 重新建立关系
        this.setSetmealAndCheckGroup(setmealId,checkgroupIds);

    }
    //移动端查询套餐信息
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    //根据套餐ID查询  对应的检查组信息 检查项信息
    @Override
    public Setmeal findAllById(Integer id) {
        return setmealDao.findAllById(id);
    }





    //查询套餐名称
    @Override
    public List<String> findSetmealNames() {
        List<String>setmealNames=setmealDao.findSetmealNames();
        return setmealNames;
    }

    //根据套餐名称查询数量
    @Override
    public List<Map<String,Object>> findOrderCountBySetmealName(List<String> setmealNames) {
        List<Map<String,Object>>setmealCounts= new ArrayList<>();

        //遍历套餐名称数组
        for (String setmealName : setmealNames) {
            Map<String,Object>map=new HashMap();
            //根据套餐名称得到相应数量
          Integer count=setmealDao.findOrderCountBySetmealName(setmealName);
          //把名称数量封装进 map 集合
          map.put("name",setmealName);
          map.put("value",count);
          //把 map 集合封装进 list集合
          setmealCounts.add(map);
         }
        return setmealCounts;
    }




    //建立两表之间关系
    public void setSetmealAndCheckGroup(Integer setmealId,Integer[] checkgroupIds){
        //获取检查项ID 需要遍历
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map=new HashMap<>();
                map.put("setmealid",setmealId);
                map.put("checkgroupid",checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }
}
